package com.dongdongshop.xxlJbo;

import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.UserService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class XxlJboText {

    @DubboReference
    private UserService userService;
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @XxlJob("sendEmail")
    public ReturnT sendEmail(){

        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);

        //邮件标题
        message.setSubject("回归老用户");
        //邮件内容
        message.setText("为了回馈老用户，我们给您准备了好多福利");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        List<TbUser> userList = userService.getAll();
        for (TbUser user : userList) {
            Date created = user.getCreated();
            c.setTime(created);
            c.add(Calendar.DATE, +7);
            Date d = c.getTime();
            if (d.before(new Date())){
                System.out.println(0);
                //谁要接收
                message.setTo(user.getEmail());
                javaMailSender.send(message);
            }
        }
        return ReturnT.SUCCESS;
    }
}
